package com.yixin.hospital.controller;

import com.yixin.hospital.common.ApiResult;
import com.yixin.hospital.common.Constant;
import com.yixin.hospital.entity.domain.Supplier;
import com.yixin.hospital.entity.dto.req.supplier.SupplierAddReqDTO;
import com.yixin.hospital.entity.dto.req.supplier.SupplierEditReqDTO;
import com.yixin.hospital.service.SupplierService;
import com.yixin.hospital.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("/supplier")
@Api(value = "供应商管理", tags = "供应商管理")
public class SupplierController {

    @Resource
    SupplierService supplierService;

    @GetMapping("/list")
    @ApiOperation(value = "供应商列表")
    public ApiResult list() {

        return ApiResult.success(supplierService.list());
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加供应商")
    public ApiResult add(@Valid @RequestBody SupplierAddReqDTO supplierAddReqDTO, HttpServletRequest request) {
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        Supplier supplier = new Supplier();
        supplier.setName(supplierAddReqDTO.getName());
        supplier.setContactName(supplierAddReqDTO.getContactName());
        supplier.setContactPhone(supplierAddReqDTO.getContactPhone());
        supplier.setCreatedBy(userName);
        supplier.setUpdatedBy(userName);
        supplierService.save(supplier);
        return ApiResult.success();
    }

    @PutMapping("/edit")
    @ApiOperation(value = "编辑供应商")
    public ApiResult edit(@Valid @RequestBody SupplierEditReqDTO supplierEditReqDTO, HttpServletRequest request) {
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        Supplier supplier = new Supplier();
        supplier.setId(supplierEditReqDTO.getId());
        supplier.setName(supplierEditReqDTO.getName());
        supplier.setContactName(supplierEditReqDTO.getContactName());
        supplier.setContactPhone(supplierEditReqDTO.getContactPhone());
        supplier.setUpdatedBy(userName);
        supplierService.updateById(supplier);
        return ApiResult.success();
    }

    @DeleteMapping("/remove/{id}")
    @ApiOperation(value = "删除供应商")
    public ApiResult remove(@PathVariable int id) {
        supplierService.removeById(id);
        return ApiResult.success();
    }

}
